package action.user;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import entity.User;
import option.OperationEnum;
import service.UserService;
import util.ClassUtil;

/**
 * 用户注册操作--填写信息
 * @author Administrator
 *
 */
@SuppressWarnings("serial")
public class RegisterServlet extends HttpServlet{
	private static Logger log = Logger.getLogger(RegisterServlet.class);
	
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String action = (String) request.getAttribute("action");
		if (action.equals(OperationEnum.USER_TOREGISTER.getValue())) {//跳转到用户注册页面
			request.getRequestDispatcher("/WEB-INF/pages/user/register_form.jsp").forward(request, response);
		} else if (action.equals(OperationEnum.USER_REGISTER.getValue())) {//用户注册
			User user = ClassUtil.parseRequestAsEntity(request, User.class);
			try {
				new UserService().saveUser(user);
				request.setAttribute("user", user);
				request.getRequestDispatcher("/WEB-INF/pages/user/verify_form.jsp").forward(request, response);
			} catch (Exception e) {
				log.error(e);
				request.setAttribute("user", user);
				request.setAttribute("errorMsg", "注册失败");
				request.getRequestDispatcher("/WEB-INF/pages/user/register_form.jsp").forward(request, response);
			}
		} else if (action.equals(OperationEnum.USER_VALIDATEEMAILVC.getValue())) {//验证邮箱验证码
			String validatecode = request.getParameter("validatecode");
			String email = request.getParameter("email");
			User user = null;
			try {
				user = new UserService().validateEmailVC(email, validatecode);
				if (user.getIs_email_verify().intValue() == 1) {
					request.setAttribute("user", user);
					request.getSession().setAttribute("user", user);
					request.getRequestDispatcher("/WEB-INF/pages/user/register_ok.jsp").forward(request, response);
				} else {
					throw new Exception();
				}
			} catch (Exception e) {
				user = new User();
				user.setEmail(email);
				request.setAttribute("user", user);
				request.setAttribute("errorMsg", "验证失败");
				request.getRequestDispatcher("/WEB-INF/pages/user/verify_form.jsp").forward(request, response);
			}
		}
	}
}
